package com.mulong.common.manager.impl;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Random;

import jakarta.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.mulong.common.manager.IdManager;
import com.mulong.common.util.SnowFlake;

import lombok.extern.slf4j.Slf4j;

/**
 * IdManagerImpl
 * 
 * @author mulong
 * @data 2021-09-23 15:33:22
 */
@Slf4j
@Component
public class IdManagerImpl implements IdManager {
    private SnowFlake snowFlake;

    @PostConstruct
    public void init() {
        long machineId;
        try {
            InetAddress address = Inet4Address.getLocalHost();
            String innerIp = address.getHostAddress();
            String endIp = StringUtils.substring(innerIp, StringUtils.lastIndexOf(innerIp, ".") + 1);
            machineId = Long.parseLong(endIp);
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            Random random = new Random();
            machineId = random.nextInt(1000);
        }
        log.info("snow flake machineId is {}", machineId);
        snowFlake = new SnowFlake(machineId);
    }

    /**
     * 下一个号
     *
     * @author mulong
     */
    @Override
    public String nextId() {
        return String.valueOf(snowFlake.nextId());
    }

    /**
     * 下一个用户侧订单号
     *
     * @author mulong
     */
    @Override
    public String nextCustomerOrderId() {
        return "C" + nextId();
    }

    /**
     * 下一个交易流水号
     *
     * @author mulong
     */
    @Override
    public String nextAccountTransactionNo() {
        return "AT" + nextId();
    }

}
